#include<vector>
#include<algorithm>
using std::vector;
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        vector<vector<int>> ret;
        for(int i =0;i<nums.size();)
        {
            long long num = target - nums[i];
            int begin = i+1;
            int end = nums.size()-1;
            for(int j = begin;j<=end;)
            {
                long long tar = num - nums[j];
                int left=j+1;
                int right=end;
                while(left<right)
                {
                    if(nums[left]+nums[right]<tar)
                    {
                        left++;
                    }
                    else if(nums[left]+nums[right]>tar)
                    {
                        right--;
                    }
                    else
                    {
                        ret.push_back({nums[i],nums[j],nums[left],nums[right]});
                        left++;
                        right--;
                        while(left<right&&nums[left]==nums[left-1]) left++;
                        while(left<right&&nums[right]==nums[right+1]) right--;
                    }
                }
                j++;
                 while(j<nums.size()&&nums[j]==nums[j-1]) j++;
            }

            //去重
            i++;
            while(i<nums.size()&&nums[i]==nums[i-1]) i++;
        }
        return ret;
    } 
};